package com.expert.config;
import com.expert.interceptor.JwtTokenInterceptor;
import com.expert.interceptor.RoleInterceptor;
import com.expert.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @ClassName: WebMvcConfig
 * @Author: cxs
 * @Date: 2024/01/18 18:41
 * @Description:
 **/
@Configuration
@Slf4j
public class WebMvcConfig  extends WebMvcConfigurationSupport {

    @Autowired
    JwtTokenInterceptor jwtTokenInterceptor;

    @Autowired
    RoleInterceptor roleInterceptor;
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("正在注册自定义拦截器....");
        super.addInterceptors(registry);
        registry.addInterceptor(jwtTokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/expert/refresh")
                .excludePathPatterns("/mail/*")
                .excludePathPatterns("/user/captchaImage");
        registry.addInterceptor(roleInterceptor);

    }

    //添加跨域
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
            // 设置允许跨域的路径
            registry.addMapping("/**")
                    // 设置允许跨域请求的域名
                    .allowedOriginPatterns("*")
                    // 是否允许cookie
                    .allowCredentials(true)
                    // 设置允许的请求方式
                    .allowedMethods("GET", "POST", "DELETE", "PUT")
                    // 设置允许的header属性
                    .allowedHeaders("*")
                    // 跨域允许时间
                    .maxAge(10000);
    }
    /**
     * 消息转换器解决Json日期的问题
     * 还可以在属性上加上@JsonFormat注解来解决，但是更麻烦
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(new JacksonObjectMapper());
        converters.add(0,converter);
    }
}
